package com.lnkj.spcj.base

import android.content.Intent
import android.content.pm.ResolveInfo
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import com.just.agentweb.AgentWeb
import com.just.agentweb.LogUtils
import com.lnkj.spcj.R
import com.lnkj.spcj.util.utilcode.ToastUtils
import kotlinx.android.synthetic.main.activity_web_view.*
import kotlinx.android.synthetic.main.layout_topbar.*
import java.net.URISyntaxException


class WebViewActivity : BaseActivity2() {
    var mAgentWeb: AgentWeb? = null
    var title: String = ""
    var url: String = ""

    override val layoutRes: Int
        get() = R.layout.activity_web_view

    override fun initAll() {
        iv_left.visibility = View.VISIBLE
        title = intent.getStringExtra("title") ?: ""
        url = intent.getStringExtra("url")
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(rl_cotainer, LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .addJavascriptInterface("android", JavaScriptinterface())
                .createAgentWeb()
                .ready()
                .go(url)
        tv_title.text = title
        iv_left.setOnClickListener { finish() }
    }

    override fun setListener() {

    }

    override fun processLogic() {
    }

    override fun onPause() {
        mAgentWeb?.getWebLifeCycle()?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.getWebLifeCycle()?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb?.getWebLifeCycle()?.onDestroy()
        super.onDestroy()
    }

    override fun onBackPressed() {
        if (!(mAgentWeb!!.back()))
            super.onBackPressed()
    }

    val mWebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, t: String?) {
            if (TextUtils.isEmpty(title))
                tv_title.text = t
        }
    }

    val mWebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, newurl: String): Boolean {
            try {
                //处理intent协议
                if (newurl.startsWith("intent://")) {
                    val intent: Intent
                    try {
                        intent = Intent.parseUri(newurl, Intent.URI_INTENT_SCHEME)
                        intent.addCategory("android.intent.category.BROWSABLE")
                        intent.component = null
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                            intent.selector = null
                        }
                        val resolves: List<ResolveInfo> = getPackageManager().queryIntentActivities(intent, 0)
                        if (resolves.size > 0) {
                            startActivityIfNeeded(intent, -1)
                        }
                        return true
                    } catch (e: URISyntaxException) {
                        e.printStackTrace()
                    }
                }
                // 处理自定义scheme协议
                if (!newurl.startsWith("http")) {
                    LogUtils.e(TAG, "处理自定义scheme-->$newurl")
                    try {
                        // 以下固定写法
                        val intent = Intent(Intent.ACTION_VIEW,
                                Uri.parse(newurl))
                        intent.flags = (Intent.FLAG_ACTIVITY_NEW_TASK
                                or Intent.FLAG_ACTIVITY_SINGLE_TOP)
                        startActivity(intent)
                    } catch (e: Exception) {
                        // 防止没有安装的情况
                        e.printStackTrace()
                        ToastUtils.showShort("您所打开的第三方App未安装！")
                    }
                    return true
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return super.shouldOverrideUrlLoading(view, newurl)
        }
    }

    inner class JavaScriptinterface {
        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        fun alreadyFound(order_sn: String) {
            runOnUiThread {

            }
        }
    }
}
